package com.aruba.provider;

import com.aruba.provider.service.impl.UserServiceImpl;
import com.aruba.rmi.service.UserService;
import org.apache.zookeeper.*;

import java.io.IOException;
import java.rmi.AlreadyBoundException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;

public class Run {

    public static void main(String[] args) throws IOException, AlreadyBoundException, InterruptedException, KeeperException {
        UserService serverService = new UserServiceImpl();
        //创建注册表
        try {
            LocateRegistry.createRegistry(8000);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        String url = "rmi://localhost:8000/userService";
        //以一个别名绑定该对象
        try {
            Naming.unbind(url);
        } catch (NotBoundException e) {
            e.printStackTrace();
        }
        Naming.bind(url, serverService);

        // 获取zooKeeper对象
        ZooKeeper zooKeeper = new ZooKeeper("192.168.42.4:2181", 10000, new Watcher() {
            @Override
            public void process(WatchedEvent watchedEvent) {
                System.out.println("连接成功");
            }
        });


        //ZooDefs.Ids.OPEN_ACL_UNSAFE 表示权限。
        //CreateMode.PERSISTENT 永久存储。
        zooKeeper.create("/demos/userService", url.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        System.out.println("服务发布成功");
    }

}
